import React, { useState, useMemo } from 'react';
import { Card, Select, Switch, Row, Col, Space, Typography } from 'antd';
import {
  LineChart,
  Line,
  AreaChart,
  Area,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  ReferenceLine
} from 'recharts';
import { LineChartOutlined, AreaChartOutlined, BarChartOutlined } from '@ant-design/icons';

const { Option } = Select;
const { Title, Text } = Typography;

interface ChartData {
  time: string;
  cityName?: string;
  [key: string]: any;
}

interface MultiMetricChartProps {
  data: ChartData[];
  title?: string;
  height?: number;
  showCityFilter?: boolean;
}

interface MetricConfig {
  key: string;
  name: string;
  unit: string;
  color: string;
  axis?: 'left' | 'right';
  type?: 'line' | 'area' | 'bar';
}

const METRIC_CONFIGS: MetricConfig[] = [
  { key: 'temperature', name: '温度', unit: '°C', color: '#ff7300', axis: 'left' },
  { key: 'humidity', name: '湿度', unit: '%', color: '#00bcd4', axis: 'right' },
  { key: 'pressure', name: '气压', unit: 'hPa', color: '#4caf50', axis: 'right' },
  { key: 'windSpeed', name: '风速', unit: 'm/s', color: '#f44336', axis: 'left' },
  { key: 'windDirection', name: '风向', unit: '°', color: '#9c27b0', axis: 'right' },
  { key: 'visibility', name: '能见度', unit: 'km', color: '#ff9800', axis: 'right' },
  { key: 'uvIndex', name: '紫外线指数', unit: '', color: '#e91e63', axis: 'left' },
];

const MultiMetricChart: React.FC<MultiMetricChartProps> = ({
  data,
  title = "多指标对比图",
  height = 400,
  showCityFilter = true
}) => {
  const [selectedMetrics, setSelectedMetrics] = useState<string[]>(['temperature', 'humidity']);
  const [chartType, setChartType] = useState<'line' | 'area' | 'bar'>('line');
  const [selectedCity, setSelectedCity] = useState<string | undefined>();
  const [showGrid, setShowGrid] = useState(true);
  const [showLegend, setShowLegend] = useState(true);
  const [smoothLine, setSmoothLine] = useState(true);

  // 获取可用的指标
  const availableMetrics = useMemo(() => {
    if (data.length === 0) return [];
    
    const sampleData = data[0];
    return METRIC_CONFIGS.filter(config => 
      sampleData.hasOwnProperty(config.key) && 
      typeof sampleData[config.key] === 'number'
    );
  }, [data]);

  // 获取城市列表
  const availableCities = useMemo(() => {
    const cities = [...new Set(data.map(item => item.cityName).filter(Boolean))];
    return cities;
  }, [data]);

  // 过滤数据
  const filteredData = useMemo(() => {
    if (!selectedCity) return data;
    return data.filter(item => item.cityName === selectedCity);
  }, [data, selectedCity]);

  // 获取选中指标的配置
  const selectedMetricConfigs = useMemo(() => {
    return METRIC_CONFIGS.filter(config => selectedMetrics.includes(config.key));
  }, [selectedMetrics]);

  // 计算Y轴域
  const getYAxisDomain = (axis: 'left' | 'right') => {
    const metrics = selectedMetricConfigs.filter(m => m.axis === axis);
    if (metrics.length === 0) return ['auto', 'auto'];

    let min = Infinity;
    let max = -Infinity;

    filteredData.forEach(item => {
      metrics.forEach(metric => {
        const value = item[metric.key];
        if (typeof value === 'number') {
          min = Math.min(min, value);
          max = Math.max(max, value);
        }
      });
    });

    if (min === Infinity) return ['auto', 'auto'];

    const padding = (max - min) * 0.1;
    return [Math.max(0, min - padding), max + padding];
  };

  const renderChart = () => {
    const leftAxisMetrics = selectedMetricConfigs.filter(m => m.axis === 'left');
    const rightAxisMetrics = selectedMetricConfigs.filter(m => m.axis === 'right');

    const commonProps = {
      data: filteredData,
      margin: { top: 5, right: 30, left: 20, bottom: 5 }
    };

    const renderMetric = (config: MetricConfig, yAxisId?: string) => {
      const props = {
        key: config.key,
        yAxisId: yAxisId || 'left',
        type: smoothLine ? 'monotone' : 'linear',
        dataKey: config.key,
        stroke: config.color,
        fill: config.color,
        strokeWidth: 2,
        name: `${config.name}(${config.unit})`
      };

      switch (chartType) {
        case 'area':
          return <Area {...props} fillOpacity={0.3} />;
        case 'bar':
          return <Bar {...props} />;
        default:
          return <Line {...props} dot={{ fill: config.color, strokeWidth: 2, r: 3 }} />;
      }
    };

    switch (chartType) {
      case 'area':
        return (
          <AreaChart {...commonProps}>
            {showGrid && <CartesianGrid strokeDasharray="3 3" />}
            <XAxis dataKey="time" />
            {leftAxisMetrics.length > 0 && (
              <YAxis 
                yAxisId="left" 
                domain={getYAxisDomain('left')}
                label={{ value: leftAxisMetrics.map(m => m.unit).join('/'), angle: -90, position: 'insideLeft' }}
              />
            )}
            {rightAxisMetrics.length > 0 && (
              <YAxis 
                yAxisId="right" 
                orientation="right"
                domain={getYAxisDomain('right')}
                label={{ value: rightAxisMetrics.map(m => m.unit).join('/'), angle: 90, position: 'insideRight' }}
              />
            )}
            <Tooltip />
            {showLegend && <Legend />}
            {selectedMetricConfigs.map(config => renderMetric(config, config.axis))}
          </AreaChart>
        );
      
      case 'bar':
        return (
          <BarChart {...commonProps}>
            {showGrid && <CartesianGrid strokeDasharray="3 3" />}
            <XAxis dataKey="time" />
            {leftAxisMetrics.length > 0 && <YAxis yAxisId="left" domain={getYAxisDomain('left')} />}
            {rightAxisMetrics.length > 0 && <YAxis yAxisId="right" orientation="right" domain={getYAxisDomain('right')} />}
            <Tooltip />
            {showLegend && <Legend />}
            {selectedMetricConfigs.map(config => renderMetric(config, config.axis))}
          </BarChart>
        );
      
      default:
        return (
          <LineChart {...commonProps}>
            {showGrid && <CartesianGrid strokeDasharray="3 3" />}
            <XAxis dataKey="time" />
            {leftAxisMetrics.length > 0 && (
              <YAxis 
                yAxisId="left" 
                domain={getYAxisDomain('left')}
                label={{ value: leftAxisMetrics.map(m => m.unit).join('/'), angle: -90, position: 'insideLeft' }}
              />
            )}
            {rightAxisMetrics.length > 0 && (
              <YAxis 
                yAxisId="right" 
                orientation="right"
                domain={getYAxisDomain('right')}
                label={{ value: rightAxisMetrics.map(m => m.unit).join('/'), angle: 90, position: 'insideRight' }}
              />
            )}
            <Tooltip />
            {showLegend && <Legend />}
            {selectedMetricConfigs.map(config => renderMetric(config, config.axis))}
            
            {/* 可选的参考线 */}
            {selectedMetrics.includes('temperature') && (
              <ReferenceLine yAxisId="left" y={0} stroke="#666" strokeDasharray="2 2" />
            )}
          </LineChart>
        );
    }
  };

  return (
    <Card title={title}>
      {/* 控制面板 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col xs={24} sm={12} md={8} lg={6}>
          <div>
            <Text strong>选择指标:</Text>
            <Select
              mode="multiple"
              placeholder="选择要显示的指标"
              style={{ width: '100%', marginTop: 4 }}
              value={selectedMetrics}
              onChange={setSelectedMetrics}
              maxTagCount={2}
            >
              {availableMetrics.map(metric => (
                <Option key={metric.key} value={metric.key}>
                  <Space>
                    <div style={{ 
                      width: 12, 
                      height: 12, 
                      backgroundColor: metric.color,
                      borderRadius: 2 
                    }} />
                    {metric.name}
                  </Space>
                </Option>
              ))}
            </Select>
          </div>
        </Col>

        <Col xs={24} sm={12} md={8} lg={6}>
          <div>
            <Text strong>图表类型:</Text>
            <Select
              value={chartType}
              onChange={setChartType}
              style={{ width: '100%', marginTop: 4 }}
            >
              <Option value="line">
                <Space><LineChartOutlined />折线图</Space>
              </Option>
              <Option value="area">
                <Space><AreaChartOutlined />面积图</Space>
              </Option>
              <Option value="bar">
                <Space><BarChartOutlined />柱状图</Space>
              </Option>
            </Select>
          </div>
        </Col>

        {showCityFilter && availableCities.length > 1 && (
          <Col xs={24} sm={12} md={8} lg={6}>
            <div>
              <Text strong>选择城市:</Text>
              <Select
                placeholder="全部城市"
                style={{ width: '100%', marginTop: 4 }}
                value={selectedCity}
                onChange={setSelectedCity}
                allowClear
              >
                {availableCities.map(city => (
                  <Option key={city} value={city}>{city}</Option>
                ))}
              </Select>
            </div>
          </Col>
        )}

        <Col xs={24} sm={12} md={8} lg={6}>
          <div>
            <Text strong>显示选项:</Text>
            <div style={{ marginTop: 4 }}>
              <Space direction="vertical" size="small">
                <Switch
                  size="small"
                  checked={showGrid}
                  onChange={setShowGrid}
                  checkedChildren="网格"
                  unCheckedChildren="网格"
                />
                <Switch
                  size="small"
                  checked={showLegend}
                  onChange={setShowLegend}
                  checkedChildren="图例"
                  unCheckedChildren="图例"
                />
                {chartType === 'line' && (
                  <Switch
                    size="small"
                    checked={smoothLine}
                    onChange={setSmoothLine}
                    checkedChildren="平滑"
                    unCheckedChildren="平滑"
                  />
                )}
              </Space>
            </div>
          </div>
        </Col>
      </Row>

      {/* 图表 */}
      <ResponsiveContainer width="100%" height={height}>
        {filteredData.length > 0 ? renderChart() : (
          <div style={{ 
            display: 'flex', 
            justifyContent: 'center', 
            alignItems: 'center', 
            height: '100%',
            color: '#999'
          }}>
            暂无数据
          </div>
        )}
      </ResponsiveContainer>

      {/* 数据统计 */}
      {filteredData.length > 0 && (
        <div style={{ marginTop: 16, padding: 16, background: '#fafafa', borderRadius: 6 }}>
          <Row gutter={16}>
            <Col span={6}>
              <Text type="secondary">数据点: </Text>
              <Text strong>{filteredData.length}</Text>
            </Col>
            <Col span={6}>
              <Text type="secondary">时间范围: </Text>
              <Text strong>
                {filteredData[0]?.time} ~ {filteredData[filteredData.length - 1]?.time}
              </Text>
            </Col>
            <Col span={12}>
              <Text type="secondary">已选指标: </Text>
              <Text strong>{selectedMetricConfigs.map(m => m.name).join('、')}</Text>
            </Col>
          </Row>
        </div>
      )}
    </Card>
  );
};

export default MultiMetricChart;